package com.glureau.aib.client.equipe;

import com.glureau.aib.shared.equipe.PionInfo;
import com.glureau.aib.shared.equipe.PionType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;

public class PionChangeHandler implements ChangeHandler {

	private final PionServiceAsync pionService = GWT.create(PionService.class);
	private PionInfo m_pionInfo;

	@Override
	public void onChange(ChangeEvent event) {
		Object source = event.getSource();
		if (source instanceof TextBox) {
			TextBox textBox = (TextBox) source;
			String sourceName = textBox.getName();
			if (sourceName.equals("name")) {
				m_pionInfo.setName(textBox.getText());
			} else if (sourceName.equals("params")) {
				m_pionInfo.setParameters(textBox.getText());
			}
		} else if (source instanceof ListBox) {
			ListBox listBox = (ListBox) source;
			String sourceName = listBox.getName();
			if (sourceName.equals("type")) {
				m_pionInfo.setType(PionType.values()[listBox
						.getSelectedIndex()]);
			} else if (sourceName.equals("ai")) {
				m_pionInfo.setAiRef(listBox.getSelectedIndex() + "");
			}
		}
		savePion(m_pionInfo);
	}

	private void savePion(PionInfo result) {
		pionService.savePion(Cookies.getCookie("sid"), result,
				new AsyncCallback<Void>() {

					@Override
					public void onSuccess(Void result) {
					}

					@Override
					public void onFailure(Throwable caught) {
						Window.alert("Warning : the modification is not saved ! Please contact the webmaster.");
					}
				});
	}

	public void setPionInfo(PionInfo pi) {
		m_pionInfo = pi;
	}
}
